import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/widget/common.dart';
import 'package:tracker/pages/home/vip_service/mixin/other_service_mixin.dart';
import 'package:tracker/pages/home/vip_service/mixin/vip_service_mixin.dart';
import 'package:tracker/pages/home/vip_service/model/vip_service_list_resp.dart';

import '../../../../provider/global_provider.dart';
import '../../../../theme/app_theme.dart';
import '../../record_history/model/device_details_resp.dart';

class OtherRecord extends ConsumerStatefulWidget {
  final int index;

  const OtherRecord({super.key, required this.index});

  @override
  ConsumerState<OtherRecord> createState() => _OtherRecordState();
}

class _OtherRecordState extends ConsumerState<OtherRecord>
    with OtherServiceMixin, VipServicePageMixin, AutomaticKeepAliveClientMixin {
  bool showLoading = true;
  DeviceDetails? deviceDetails;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      actionType = widget.index;
      if (actionType == 3) {
        getDeviceInfo().then((value) {
          deviceDetails = value.data;
        });
      }


      getPackageList(actionType + 1).then((value) {

        XLogger.info(actionType);
        if (actionType == 1 || actionType == 3) {
          highVipServiceData.clear();
          highVipServiceData.addAll(value.data ?? []);
        } else {
          recordVipServiceData.clear();
          recordVipServiceData.addAll(value.data ?? []);
        }
        showLoading = false;
        setState(() {});
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return showLoading
        ? Container(
            alignment: Alignment.center,
            child: CircularProgressIndicator(
              color: AppTheme.themeConfig.primaryColor,
            ),
          )
        : (getVipData().isNotEmpty ? buildBody() : const Center());
  }

  Widget buildBody() {
    return Padding(
      padding: const EdgeInsets.only(left: 14, right: 14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              child: ListView.separated(
                  padding: const EdgeInsets.only(top: 20),
                  shrinkWrap: true,
                  // physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index) {
                    if (index == getVipData().length) {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Padding(
                              padding: const EdgeInsets.only(
                                  top: 14, left: 10, right: 10),
                              child: lpText("服务内容:")),
                          Padding(
                              padding: EdgeInsets.symmetric(horizontal: 10),
                              child: lpText(
                                  getVipData()[getSelectIndex()].content ?? "",
                                  size: 14)),
                            if (index == 3)
                            SizedBox(
                              height: 12,
                            ),
                            if (index == 3)
                            Padding(
                                padding: EdgeInsets.symmetric(horizontal: 10),
                                child:
                                (deviceDetails?.positionDay ?? 0) == -1 ? lpText( '剩余天数: 终身', size: 14) : lpText( '剩余天数:${deviceDetails?.positionDay ?? 0}', size: 14)),
                        ],
                      );
                    }
                    return buildVip(index);
                  },
                  separatorBuilder: (context, index) {
                    return const SizedBox(height: 10);
                  },
                  itemCount: getVipData().length + 1)),
          Container(
            margin: const EdgeInsets.only(top: 16),
            alignment: Alignment.center,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                lpText("支付方式:"),
                const SizedBox(width: 10),
                buildContainer(
                    title: "支付宝",
                    image: "assets/images/pay/alipay_logo.png",
                    index: 0),
                const SizedBox(width: 10),
                buildContainer(
                    title: "微信",
                    image: "assets/images/pay/wxpay_logo.png",
                    index: 1)
              ],
            ),
          ),
          GestureDetector(
            onTap: payVip,
            child: Container(
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width,
              margin: const EdgeInsets.only(
                  left: 24, right: 24, top: 20, bottom: 30),
              padding: const EdgeInsets.symmetric(vertical: 8),
              decoration: BoxDecoration(
                  color: AppTheme.themeConfig.primaryColor,
                  borderRadius: BorderRadius.circular(20)),
              child: lpText("确认并支付 ¥${getVipData()[getSelectIndex()].price}",
                  color: Colors.white, size: 16),
            ),
          )
        ],
      ),
    );
  }

  void payVip() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (actionType == 1 || actionType == 3) {
      if (highPayIndex == 0) {
        alipayUtils.createVip(
            highVipServiceData[highIndex].packageId?.toInt(),
            deviceInfo.imei.toString());
      } else {
        wxpayUtils.createVip(
            highVipServiceData[highIndex].packageId?.toInt(),
            deviceInfo.imei.toString(), highVipServiceData[highIndex].price?.toDouble());
      }
    } else {
      if (recordPayIndex == 0) {
        alipayUtils.createVip(
            recordVipServiceData[recordIndex].packageId?.toInt(),
            deviceInfo.imei.toString());
      } else {
        wxpayUtils.createVip(
            recordVipServiceData[recordIndex].packageId?.toInt(),
            deviceInfo.imei.toString(), recordVipServiceData[recordIndex].price?.toDouble());
      }
    }

  }

  Widget buildContainer(
      {required String image, required String title, required int index}) {
    return GestureDetector(
      onTap: () {
        setState(() {
          if (actionType == 1 || actionType == 3) {
            highPayIndex = index;
          } else {
            recordPayIndex = index;
          }
        });
      },
      child: Container(
        constraints: const BoxConstraints(minWidth: 100),
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
        decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(
                color: getPayIndex() == index
                    ? AppTheme.themeConfig.primaryColor
                    : AppTheme.themeConfig.secondaryTextColor.withOpacity(0.6),
                width: getPayIndex() == index ? 3 : 2)),
        child: Row(
          children: [
            Image.asset(image, width: 26, height: 26),
            const SizedBox(width: 6),
            lpText(title, size: 14)
          ],
        ),
      ),
    );
  }

  Widget buildVip(int index) {
    VipServiceData data = getVipData()[index];
    bool isSelect = index == highIndex;
    return GestureDetector(
        onTap: () {
          if (actionType == 1 || actionType == 3) {
            highIndex = index;
          } else {
            highIndex = index;
          }
          setState(() {});
        },
        child: AspectRatio(
            aspectRatio: 4.78,
            child: Stack(
              alignment: Alignment.centerRight,
              children: [
                if (actionType == 2)
                Image.asset("assets/images/vip/icon_vip_grey_bg.png"),
                if (actionType == 1 || actionType == 3)
                  Image.asset(isSelect
                      ? "assets/images/vip/icon_vip_border_bg.png"
                      : "assets/images/vip/icon_vip_grey_bg.png"),
                if (isSelect && (actionType == 1 || actionType == 3))
                  Image.asset("assets/images/vip/icon_vip_blue_bg.png"),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20),
                  child: Row(
                    children: [
                      if (actionType == 2)
                      Expanded(
                          child: lpText(data.title ?? "",
                              size: 22, color: AppTheme.themeConfig.primaryColor)),
                      if (actionType == 2)
                      RichText(
                          text: TextSpan(children: [
                            TextSpan(
                                text: "${data.price}",
                                style: TextStyle(
                                    fontSize: 26,
                                    color: isSelect ? AppTheme.themeConfig.primaryColor : AppTheme.themeConfig.secondaryTextColor)),
                            TextSpan(
                                text: " 元",
                                style: TextStyle(
                                    color: isSelect ? AppTheme.themeConfig.primaryColor : AppTheme.themeConfig.secondaryTextColor,
                                    fontSize: 18)),
                          ])),
                      if (actionType == 1 || actionType == 3)
                        Expanded(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                lpText(data.title ?? "", size: 22),
                                // lpText(data.subtitle ?? "")
                              ],
                            )),
                      if (actionType == 1 || actionType == 3)
                        RichText(
                            text: TextSpan(children: [
                              TextSpan(
                                  text: "${data.price}",
                                  style: TextStyle(
                                      fontWeight: isSelect
                                          ? FontWeight.bold
                                          : FontWeight.normal,
                                      fontSize: isSelect ? 35 : 26,
                                      color: isSelect ? Colors.white : Colors.black)),
                              TextSpan(
                                  text: " 元",
                                  style: TextStyle(
                                      color: isSelect ? Colors.white : Colors.black,
                                      fontSize: isSelect ? 15 : 26)),
                            ]
                            )
                        )
                    ],
                  ),
                )
              ],
            )
          ),
    );
   }

  @override
  bool get wantKeepAlive => true;
}
